<template>
  <div class="theme-content-item" style="position: relative;">
    <div class="padding-20px form-style">
      <div class="left-title">{{ title }}</div>
      <el-form ref="bannerFormRef" label-width="120px" :model="form" :rules="rules"
        style="margin-top: 40px">
        <el-row style="display: flex;justify-content:start">
          <el-col :span="10">
            <el-form-item label="标题" prop="name">
              <el-input v-model="form.title" placeholder="请输入标题"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="排序" prop="orderNum">
              <el-input type="number" v-model="form.orderNum" placeholder="请输入排序号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="所属类别" prop="catalogCode">
              <el-select clearable v-model="form.catalogCode" placeholder="请选择类别">
                <el-option v-for="item in data.catalogList" :key="item.code" :label="item.name" :value="item.code"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="关联URL" prop="linkUrl">
              <el-input v-model="form.linkUrl" placeholder="请输入URL"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="10">
              <el-form-item label="关联课程" prop="courseTypeList">
                <el-select clearable v-model="form.courseTypeList" placeholder="请选择课程" multiple :collapse-tags="true" :collapse-tags-tooltip="true">
                  <el-option v-for="item in data.courseList" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="所属地区" prop="provinceIdList">
              <el-select clearable v-model="form.provinceIdList" placeholder="请选择地区" multiple :collapse-tags="true" :collapse-tags-tooltip="true">
                <el-option :key="'select-all'" :label="'全选'" :value="null" @click.stop="toggleSelectAll"/>
                <el-option v-for="item in data.areaList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="状态" prop="publishedFlag">
              <el-radio v-model="form.publishedFlag" :label="1">上架</el-radio>
              <el-radio v-model="form.publishedFlag" :label="0">下架</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="图片" prop="avatarPicUrl">
              <el-upload class="avatar-uploader" name="fileList" :action="$uploadUrl" :headers="headers" :show-file-list="false"
                         :on-success="handleUploadSuccess" :on-error="handleUploadError" accept=".jpeg,.png,.jpg,.bmp">
                <img style="width: 180px; height: 120px; object-fit: scale-down;" v-if="form.imageUrl" :src="form.imageUrl"
                     class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style=" position: fixed; bottom: 5%; left: 45%" class="flex-jc-s-b">
        <el-button size="small" @click="goBack()">
          <svg-icon icon-class="back" class="el-input__icon input-icon" />
          <span style="margin-left: 5px;">关 闭</span>
        </el-button>
        <el-button size="small" style="margin-left: 20px;" type="primary" @click="save">
          <svg-icon icon-class="save" class="el-input__icon input-icon" />
          <span style="margin-left: 5px;">保 存</span>
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { getToken } from '@/utils/auth'
import {addBanner, editBanner, getBannerDetail} from '@/api/config/banner'
import {listDictItemByCode} from '@/api/config/dic'
const headers = ref({ Authorization: "Bearer " + getToken() });
const { proxy } = getCurrentInstance();
const route = useRoute()
const router = useRouter()
const routeQuery = reactive(route.query)
const title = ref('');
const isAdd = ref(false);
const data = reactive({
  courseList: [],
  areaList: [],
  catalogList: [
    {name: '首页',code: 'courseIndexCode'},{name: '课程中心',code: 'courseCenterCode'},
  ],
})
const form = reactive({
  id: null,
  title: '',
  orderNum: '',
  catalogCode: '',
  publishedFlag: 1,
  linkUrl: '',
  imageUrl: '',
  courseTypeList: [],
  provinceIdList: [],
})

const rules = ({
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  orderNum: [{ required: true, message: '请输入排序号', trigger: 'blur' }],
  linkUrl: [{ required: true, message: '请输入URL', trigger: 'blur' }],
  catalogCode: [{ required: true, message: '请选择类型', trigger: 'blur' }],
  publishedFlag: [{ required: true, message: '请选择状态', trigger: 'blur' }],
  imageUrl: [{ required: true, message: '请选择图片', trigger: 'blur' }],
  courseTypeList: [{ required: true, message: '请选择课程', trigger: 'blur' }],
  provinceIdList: [{ required: true, message: '请输入地区', trigger: 'blur' }],
})
const toggleSelectAll = () => {
  if (form.provinceIdList.length-1 === data.areaList.length) {
    form.provinceIdList = [];
  } else {
    form.provinceIdList = data.areaList.map(option => option.id);
  }
};
function handleUploadSuccess(response) {
  form.imageUrl = response.data[0].url
  ElMessage({ message: "上传成功", type: 'success' })
}
function handleUploadError(Error) {
  ElMessage.error("上传失败")
}

// 详情
const initDetail = (row) => {
  getBannerDetail(row.id || route.query.id).then((res) => {
    let resData = res.data
    Object.keys(form).forEach((key) => { form[`${key}`] = resData[`${key}`] })
    form.courseTypeList = []
    form.provinceIdList = []
    resData.courseTypeMap.map(item => {
      form.courseTypeList.push(item.id)
    })
    resData.provinceMap.map(item => {
      form.provinceIdList.push(item.id)
    })
  })
}
const initData = () => {
  listDictItemByCode({typeCode: 'courseTypeCode'}).then(res => {
    data.courseList = res.rows
  })
  listDictItemByCode({typeCode: 'regionCode'}).then(res => {
    data.areaList = res.rows
  })
}

// function changeCourseHandle() {
//   let courseTypeRef = proxy.$refs["courseTypeRef"]
//   // let pathLabels = courseTypeRef.getCheckedNodes()[0].pathLabels
//   // form.courseName = pathLabels[0] + '-' +pathLabels[1]
// }

const save = () => {
  proxy.$refs["bannerFormRef"].validate(valid => {
    if (valid) {
      if (isAdd.value) {
        addBanner(form).then(res => {
          if (res.code === 200) {
            clearForm()
            ElMessage.success('新增成功');
          }
        })
      } else {
        editBanner(form).then(res => {
          if (res.code === 200) {
            ElMessage.success('修改成功');
          }
        })
      }
    }
  })
}
function goBack() {
  proxy.$tab.closeOpenPage();
  router.go(-1)
}
function clearForm() {
  Object.keys(form).forEach((key)=>{
    form[key] = ''
  })
  form.publishedFlag = 1
}

onMounted(() => {
  let titleMap = {
    add: '新增',
    edit: '修改',
  }
  routeQuery.type ? title.value = titleMap[routeQuery.type] : ''
  routeQuery.type == 'edit' ? initDetail(route.query) : ''
  isAdd.value = routeQuery.type == 'add'
  initData()
})
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  text-align: center;
}
</style>
